
import arxiv

def lcsamilarity(X, Y):
    m = len(X)
    n = len(Y)
    L = [[0] * (n + 1) for i in range(m + 1)]
    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0 or j == 0:
                L[i][j] = 0
            elif X[i - 1] == Y[j - 1]:
                L[i][j] = L[i - 1][j - 1] + 1
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])
    lcs_ratio = 2 * L[m][n] / ( m + n )
    return lcs_ratio


from meta_service.utils import format_title

def SearchEntryId(title:str):
    results = arxiv.Client().results(arxiv.Search(
        query=str(title),
        max_results=5,
    ))

    def get_seq(line:str):
        all = "".join([ ch.lower() for ch in line if ch.isalpha() ])
        return all

    sftitle = get_seq(format_title(title))
    lis = []
    for data in results:
        ftitle = get_seq(format_title(data.title))
        lcsa = lcsamilarity(sftitle,ftitle)
        entry_id = str(data.entry_id)
        entry_id = entry_id.split("/")[-1]
        lis.append((lcsa,entry_id,data.title))
    if len(lis) > 0:
        lis = sorted(lis,key=lambda x:x[0],reverse=True)
        lcsa,entry_id,title = lis[0]
        if lcsa >= 0.95:
            return entry_id,title
    return None,None

# def test_init_tis_store():
#     from meta_service.tistore import MAIN_TIS
#     # # topic_list = MAIN_TIS.GetTopicList()
#     # # print(topic_list)
#     # handle = None
#     # if MAIN_TIS.HasTopic("openreview.iclr.2025"):
#     #     handle = MAIN_TIS.GetTopicHandle("openreview.iclr.2025")
#     # index_list = handle.GetIndexList()
#     # print(index_list)

# from extra_service.openreview import *
# def test_load_from_tis():
#     none_count = 0
#     from meta_service.tistore import MAIN_TIS
#     if MAIN_TIS.HasTopic("rematch"):
#         handle = MAIN_TIS.GetTopicHandle("rematch")
#         # count = CountPaperInTisHandle(handle)
#         papers = LoadPaperFromTisHandle(handle,20)
#         for paper in papers:
#             title = paper.get_title()
#             entry_id,res = SearchEntryId(title)
#             if entry_id is None:
#                 none_count += 1
#     print(none_count)


# test_load_from_tis()

